import base64
from io import BytesIO

import bencodepy
from flask import Flask, request, jsonify, send_file
from flask_cors import CORS
import torrent_parser as tp
import CheatAnalyzer

app = Flask(__name__)
CORS(app)

# JSONIFY_MODEL = "hex"
JSONIFY_MODEL = "base64"

TorrentStoragePath = "/torrents"


@app.route('/torrent/parse_torrent', methods=['POST'])
def parse_torrent():
    try:
        # 文件验证
        file = request.files.get('torrent')
        if not (file and file.filename.endswith('.torrent')):
            return jsonify({"error": "未收到有效种子文件"}), 400
        parse_model = request.form.get('parse_model')

        total_length, info_hash = tp.parser(file.read())

        if parse_model == "base64":
            return jsonify({
                "length": total_length,
                # "hash_info": base64.b64encode(hash_info).decode('utf-8'),
                "info_hash": base64.b64encode(info_hash).decode('utf-8')
            })
        elif parse_model == "hex":
            return jsonify({
                "length": total_length,
                # "hash_info": hash_info.hex(),
                "info_hash": info_hash.hex()
            })
        else:
            return jsonify({"error": "unrecognized parse model"}), 400
    except KeyError as e:
        return jsonify({"error": f" {e}"}), 400
    except bencodepy.DecodingError:
        return jsonify({"error": "Invalid Bencode format"}), 400


@app.route("/torrent/modify_torrent", methods=['POST'])
def modify_torrent():
    try:
        # 文件验证
        file = request.files.get('torrent')
        if not (file and file.filename.endswith('.torrent')):
            return jsonify({"error": "未收到有效种子文件"}), 400

        passkey = request.form.get('passkey')
        if not passkey:
            return jsonify({"error": "缺少 passkey 参数"}), 400

        torrent = tp.torrent_passkey_modify(file.read(), passkey)
        # return send_file(BytesIO(torrent), mimetype='application/octet-stream')
        return send_file(
            BytesIO(torrent),
            mimetype='application/x-bittorrent',
            as_attachment=True,
            download_name=file.filename  # Flask >= 2.0 支持，旧版本使用 attachment_filename
        )


    except KeyError as e:
        return jsonify({"error": f"Missing key in torrent: {e}"}), 400
    except bencodepy.DecodingError:
        return jsonify({"error": "Invalid Bencode format"}), 400

@app.route("/cheat/data", methods=['GET'])
def cheat_detect():
    # 初始化分析器
    analyzer = CheatAnalyzer.CheatAnalyzer("mysql+pymysql://hqz:123456@localhost/ptproject")

    # 执行分析
    result = analyzer.run_analysis()

    # 返回成功响应
    return jsonify({
        "status": "success",
    }), 200






# @app.route('/compress_image', methods=['POST'])
# def parse_torrent():
#     img = request.files['cover']
#     # 转换模式（解决RGBA兼容性问题）
#     if img.mode in ('RGBA', 'LA'):
#         img = img.convert('RGB')
#
#     current_quality = 85  # 初始质量
#     img_byte = io.BytesIO()
#
#     img.save(img_byte, format='JPEG', quality=current_quality, optimize=True)
#
#     # 锐化处理（补偿清晰度损失）[1](@ref)
#     img = img.filter(ImageFilter.SHARPEN)
#
#     return img


if __name__ == '__main__':
    # 启动应用
    app.run(host='127.0.0.1', port=5000)
